package com.apestech.api.condition;

import com.apestech.api.tables.TableExec;
import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.formwork.condition.ExecAccountExcute;
import com.apestech.formwork.condition.ExecAccountSave;
import com.apestech.formwork.xml.XmlQuery;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.SaveTablesCallback;
import com.apestech.framework.xml.condition.modul.Account;
import com.apestech.framework.xml.plugin.XmlPaste;
import com.apestech.framework.xml.table.modul.Tables;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-03-05-11:38
 */
public class AccountExec extends ConditionUtil {
    private Account account;
    private String accountId;
    private ConditionExec conditionExec;
    private XmlPaste xmlPaste;

    public AccountExec(SqlSession session, String accountId) throws Exception {
        this.accountId=accountId;
        xmlPaste=new XmlPaste(accountId, "accountDef", session);
        init();
    }

    public AccountExec(XmlQuery xmlQuery, String accountId) throws Exception {
        this.accountId=accountId;
        xmlPaste=new XmlPaste(accountId, "accountDef", xmlQuery);
        init();
    }

    public Account getAccount() {
        return account;
    }

    private void init() throws Exception {
        xmlPaste.expain();
        account=xmlPaste.getAccount();
        if(account==null) throw new Exception("请输入合法的帐目ID["+accountId+"]！");
        conditionExec=new ConditionExec(xmlPaste.getXmlQuery(), account.getId());
        account.setConditon(conditionExec.getCondition());
        ConditionStrategyExec conditionStrategyExec=new ConditionStrategyExec(xmlPaste.getXmlQuery(), account.getConditionStrategy());
        account.setStep(conditionStrategyExec.getConditionStrategy().getStep("condition."+account.getConditon().getId()));
        ArrayList<String> list=account.getBillKey();
        int len=list.size();
        for(int i=0; i<len; i++){
            String bid=list.get(i);
            Tables table=null;
            Account.Bill bill=account.getBill(bid);
            ArrayList<String> blist=bill.getTableList();
            int blen=blist.size();
            for(int b=0; b<blen; b++){
                Account.UpdateTable updateTable= bill.getUpdateTable(blist.get(b));
                xmlPaste=new XmlPaste(bill.getMaster(), "tables", xmlPaste.getXmlQuery());
                table=xmlPaste.getTable();
                if(table==null){
                    table=xmlPaste.getXmlQuery().getSession().getTables(bill.getMaster());
                    if(table==null) throw new Exception("请检查：bill配置下["+bid+"]结点里的master信息["+bill.getMaster()+"]配置有误！");
                }
                bill.setTable(table);
                BillTable billTable=getBillOrder(updateTable.getUpdate(), account, updateTable.getFields(), xmlPaste.getXmlQuery().getSession());
                updateTable.setBillTable(billTable);
                bill.setUpdateTable(updateTable);
                account.setBill(bid, bill);
                account.createBillExtandTable(bill, blist.get(b));
            }
        }
    }

    public void delete(String tableName, JSONObject data) throws Exception {
        Account.Bill bill=account.getBillFromUpdate(tableName);
        String update=bill.getUpdateTable(tableName).getBillTableName();
        xmlPaste.getXmlQuery().getSession().getForUpdate().deleteTable(update,bill.getTable().getParentIdDataMap(update, data));
    }

    public void insert(String tableName, JSONObject data) throws Exception {
        xmlPaste.getXmlQuery().getSession().getForUpdate().insertTable(account.getUpdateTable(tableName).getBillTableName(), data);
    }

    public void saveBill(String master, Object param, boolean insert, boolean query, SaveTablesCallback saveTablesCallback) throws Exception {
        if(param==null) return;
        JSONObject jparam=null;
        JSONArray dlist=new JSONArray();
        if(param instanceof JSONObject){
            jparam= (JSONObject) param;
            if(jparam.size()>0) dlist.add(jparam);
        }
        else if(param instanceof JSONArray) dlist.addAll((JSONArray)param);
        int dlen=dlist.size();
        if(dlen==0) return;
        Account.Bill bill=account.getBill(master);
        TableExec table=new TableExec(xmlPaste.getXmlQuery().getSession(), bill.getTable());
        for(int i=0; i<dlen; i++){
            JSONObject keyMap=bill.getTable().getMasterIdDataMap(dlist.get(i));
            table.execTable(new ExecAccountSave(bill, insert, query, keyMap, saveTablesCallback), dlist.get(i));
        }
    }

    public void excuteBill(String master, Object param, String executeId, SaveTablesCallback saveTablesCallback) throws Exception {
        if(param==null) return;
        JSONObject jparam=null;
        JSONArray dlist=new JSONArray();
        if(param instanceof JSONObject){
            jparam= (JSONObject) param;
            if(jparam.size()>0) dlist.add(jparam);
        }
        else if(param instanceof JSONArray) dlist.addAll((JSONArray)param);
        int dlen=dlist.size();
        if(dlen==0) return;
        Account.Bill bill=account.getBill(master);
        TableExec table=new TableExec(xmlPaste.getXmlQuery().getSession(), bill.getTable());
        for(int i=0; i<dlen; i++){
            table.execTableAccount(dlist.get(i), new ExecAccountExcute(account, bill, executeId, saveTablesCallback));
        }
    }



//LSD, LSDITEM, 官设LSDSPMX, 动态LSDITEM_序号, LSDSK
        /*
        LSD 记数据 saveTable
        LSDITEM动态其实与它用平级表，循环取数，先恢复所有明细下的涉及到的帐目
          执行删除，先明细再主表
          INSERT数据先插入主表LSDITEM，依次插入动态明细、已写代码的明细
        LSSPMX
        LSDSK
        */



}
